

import tornado.web                          #第三方模块tornado       需要下载  web小型框架 使用IO多路复用
import tornado.ioloop                       #第三方模块tornado       需要下载  web小型框架 使用IO多路复用
import os,sys,json                          #内置标准库              os文件操作、sys系统操作、json数据类型
import yaml                                 #第三方模块yaml          需要下载  是一个配置文件解析的第三方模块
import requests

URL_={
    'get_data':'/tperiptweprtrwet4',
    'type':'/hjfkhsdahfiwhja',
    'stop':'/kjdsfkaslwoeidfjsa'
}
run_func=[None]
type_val=False
close_fun=None
class handle(tornado.web.RequestHandler):
    # #self.json_body自动转为dict
    def prepare(self):
        try:
            self.json_body = json.loads(self.request.body)
        except ValueError:
            self.json_body = {}
    def post(self):
        # print(1)
        # print(2,self.json_body,type(self.json_body))
        try:
            if run_func[0]is not None:
                res=run_func[0](**self.json_body)
                if res in (True,False,None):
                    res={'type':res}
                # print('res',res,type(res))
                self.write(res)
        except Exception as e:
            print(' is None',e)
class handle_type(tornado.web.RequestHandler):
    type=False
    # #self.json_body自动转为dict
    def prepare(self):
        try:
            self.json_body = json.loads(self.request.body)
        except ValueError:
            self.json_body = {}
    def post(self):
        new_type=self.json_body.get('set_type')
        if new_type is not None:
            global type_val
            type_val=new_type
        
        self.write({'type':type_val})
class stop_(tornado.web.RequestHandler):  
    def post(self):
        loop = tornado.ioloop.IOLoop.instance()  
        loop.stop()  
        if close_fun is not None:
            close_fun()
        self.write({'type':'success'})
def set_http(func,process_type=False,url_lst=None,close_func=None,port=8888,ip='127.0.0.1',**k):
    global run_func,type_val,close_fun
    close_fun=close_func
    if url_lst is None:url_lst=[]
    run_func[0]=func
    type_val=process_type
    app = tornado.web.Application([
        (URL_['get_data'], handle),
        (URL_['type'],handle_type),
        (URL_['stop'],stop_),
        *url_lst
        ],**k)
    app.listen(port)
    tornado.ioloop.IOLoop.current().start()
class Get_client:
    def __init__(self,ip,port):
        # print(url,ip,port)
        self.url='http://'+ip+':'+str(port)
        # print('url',self.url)
        self.headers = {'Content-Type': 'application/json'}
    def post(self,**kwargs):# 发送POST请求，并将JSON数据作为请求体传递
        # print('post kwargs',kwargs)
        response = requests.post(self.url+URL_['get_data'], data=json.dumps(kwargs), headers=self.headers)
        # print(response.text)
        return response.text
    def set_type(self,type_val=True):
        requests.post(self.url+URL_['type'], data=json.dumps({'set_type':type_val}), headers=self.headers)
    def get_type(self):
        res = requests.post(self.url+URL_['type'], data=json.dumps({}), headers=self.headers)
        return json.loads(res.text)['type']
    def stop(self):
        res = requests.post(self.url+URL_['stop'], data=json.dumps({}), headers=self.headers)
        return json.loads(res.text)['type']
def get_client(port=8888,ip='127.0.0.1'):
    return Get_client(ip,port)

if __name__=='__main__':
    config_dct={
        "ip": "127.0.0.1",
        "port": 8000,
            }
    # set_http(lambda :None,**config_dct)
    g=get_client(**config_dct)
    # val=g.post(db_name='color_db',db_handle_type='get',condition_field=['id',2])
    g.set_type(type_val=False)
    type=g.stop()
    print(type)

